import React, { useRef } from 'react';
import { Layout, message } from 'antd';
import ToolBox from './tool/ToolBox';
import ToolBar from './tool/ToolBar';
import Graphic from './Graphc';
import * as events from '../../utils/event/componentEvent';
import { NODE } from './utils/constants';
import { randomKey } from '../../utils/utils';
import { getComponent } from './utils/component';

import { ADD_UNDO_MANAGER, eventEmitter } from './utils/event';
import './index.less';
import 'intro.js/introjs.css';

export default function Flow(props) {
  console.log(978, props);
  const _graph = useRef(); // 画布对象
  const _graphWrap = useRef(); // 画布框对象

  //改变用户行为mode
  function handleAdd(x, y, componentName, sourceId) {
    const graph = _graphWrap.current.getBoundingClientRect();
    const _x = x - graph.x;
    const _y = y - graph.y;
    // 如果想x||y中任何一个超出边界,即没有在画布中，则return
    if (_x < 0 || _y < 0) {
      return;
    }
    return addNode(
      _graph.current.getPointByClient(x, y).x,
      _graph.current.getPointByClient(x, y).y,
      componentName,
      sourceId,
    );
  }

  function addNode(x, y, componentName, sourceId) {
    console.log(componentName, getComponent(componentName));
    const limitComponents = [NODE._START];
    let isLimit = false;
    const nodes = _graph.current.getNodes();
    nodes.forEach((item) => {
      const currentShape = item.getModel().shape;
      // 如果是start,end中的一个，且
      if (
        limitComponents.includes(currentShape) &&
        limitComponents.includes(componentName) &&
        componentName === currentShape
      ) {
        isLimit = true;
      }
    });
    if (!isLimit) {
      const id = randomKey(); // 生成唯一的 id
      if (componentName === NODE._STRATEGY) {
        events.eventEmitter.emit(events.OPEN_STRATEGY_NODE, {
          data: {
            x: x,
            y: y,
            id,
            ...getComponent(componentName),
          },
          actionType: 'add',
          sourceId: sourceId ? sourceId : '',
        });
        //如果是动作节点
      } else if (componentName === NODE._ACTION) {
        events.eventEmitter.emit(events.OPEN_ACTION_NODE, {
          data: {
            x: x,
            y: y,
            id,
            ...getComponent(componentName),
          },
          actionType: 'add',
          sourceId: sourceId ? sourceId : '',
        });
      } //如果是挑战者节点
      else if (componentName === NODE._CHALLENGE) {
        events.eventEmitter.emit(events.OPEN_CHALLENGE_NODE, {
          data: {
            x: x,
            y: y,
            id,
            ...getComponent(componentName),
          },
          actionType: 'add',
          sourceId: sourceId ? sourceId : '',
        });
      } else {
        _graph.current.addItem('node', {
          x: x,
          y: y,
          id,
          ...getComponent(componentName),
        });
        eventEmitter.emit(ADD_UNDO_MANAGER, {
          undo: function() {
            const item = _graph.current.findById(id);
            _graph.current.removeItem(item);
          },
          redo: function() {
            _graph.current.addItem('node', {
              x: x,
              y: y,
              id,
              ...getComponent(componentName),
            });
          },
        });
      }

      return id;
    } else {
      message.warning(componentName === NODE._START ? '已存在开始节点' : '已存在结束节点');
      return null;
    }
  }

  function addEdge(sourceId, targetId, label, percent) {
    const option = {
      source: sourceId,
      target: targetId,
      shape: 'line-arrow',
      id: randomKey(),
    };
    console.log(option);
    if (label !== undefined) {
      option.label = label;
    }
    if (percent !== undefined) {
      option.percent = percent;
    }
    _graph.current.addItem('edge', option);
  }

  function handleRef(ref) {
    _graph.current = ref;
    props.onRef && props.onRef(_graph.current);
  }
  // function openStep() {
  //   if (props.localSubmit) {
  //     // modal-con-wp
  //     var innerH = document.querySelector('.modal-con-wp').clientHeight;
  //     document.querySelector('.tantuer-modal-inner').scrollTop = innerH;
  //     introJs('#intro-farm')
  //       .setOption('prevLabel', '上一步')
  //       .setOption('nextLabel', '下一步')
  //       .setOption('skipLabel', '跳过')
  //       .setOption('doneLabel', '知道了')
  //       .setOption('tooltipClass', 'tooltip-tantuer')
  //       .setOption('highlightClass', 'highlight-tantuer')
  //       .start();
  //   } else {
  //     introJs()
  //       .setOption('prevLabel', '上一步')
  //       .setOption('nextLabel', '下一步')
  //       .setOption('skipLabel', '跳过')
  //       .setOption('doneLabel', '知道了')
  //       .setOption('tooltipClass', 'tooltip-tantuer')
  //       .setOption('highlightClass', 'highlight-tantuer')
  //       .start();
  //   }
  // }

  return (
    <>
      <Layout className='flow-graphic-wp'>
        {!props.disabled && (
          <Layout.Sider width={100} className='flow-aside'>
            <ToolBox onAdd={handleAdd} />
            {/* <div
              onClick={() => openStep()}
              style={{ position: 'absolute', bottom: '20px', left: '0', width: '100%', textAlign: 'center' }}
            >
              使用帮助
              <Icon type='question-circle' className='cursor' style={{ marginLeft: '5px' }} />
            </div> */}
          </Layout.Sider>
        )}
        <Layout.Content>
          <Layout>
            {!props.disabled && (
              <Layout.Header style={{ padding: '12px 50px 0 0' }} className='flow-hd'>
                <ToolBar _graph={_graph} _graphWrap={_graphWrap} disabled={props.disabled} />
              </Layout.Header>
            )}

            <Layout.Content>
              <div ref={(ref) => (_graphWrap.current = ref)}>
                <Graphic
                  {...props}
                  wp={props.wp}
                  onRef={(ref) => handleRef(ref)}
                  value={props.value}
                  graphicMode={props.graphicMode}
                  onAdd={handleAdd}
                  onAddEdge={addEdge}
                />
              </div>
            </Layout.Content>
          </Layout>
        </Layout.Content>
      </Layout>
    </>
  );
}
